package com.euq.service.Impl;

import com.euq.entity.Cfg;
import com.euq.mapper.CfgMapper;
import com.euq.service.CfgService;
import com.euq.utils.BeanUtils;
import com.euq.utils.EuqException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CfgServiceImpl implements CfgService {
    @Autowired
    private CfgMapper cfgMapper;
    @Override
    public PageInfo<Cfg> listCfg(int page,int size) {
        PageHelper.startPage(page, size);
        List<Cfg> Cfgs = cfgMapper.listAll();
        return new PageInfo<>(Cfgs);
    }
    @Override
    @CacheEvict(value = "cfgCache", allEntries = true)
    public void deleteCfg(Long id) {
        if(id == null){
            throw new EuqException("9999","id不能为空");
        }
        Cfg cfg = cfgMapper.getCfgById(id);
        if (cfg == null) {
            throw new EuqException("9999","输入ID错误");
        }
        cfgMapper.deleteCfg(id);
    }
    @Override
    @CacheEvict(value = "cfgCache", allEntries = true)
    public void insertCfg(String cfgName, String cfgValue, String cfgDescription) {
        if (BeanUtils.isOneEmpty(cfgName, cfgValue, cfgDescription)) {
            throw new EuqException("9999","输入参数不能为空");
        }
        Cfg cfg =cfgMapper.getCfgByCfgName(cfgName);
        if (cfg != null) {
            throw new EuqException("9999","参数已存在");
        }
        cfgMapper.addCfg(cfgName,cfgValue,cfgDescription);
    }

    @Override
    @Cacheable(value="cfgCache",
                key="T(String).format('%d,%d,%s,%s',#page,#size,#cfgName,#cfgValue)")
    public PageInfo<Cfg> selectCfg(int page, int size, String cfgName, String cfgValue) {
        PageHelper.startPage(page, size);
        List<Cfg> cfgs = cfgMapper.selectByConditions(cfgName,cfgValue);
        return new PageInfo<>(cfgs);
    }
}
